<?php
/**
 * @Copyright
 * @package    	EasyCalcCheck Plus
 * @author		Viktor Vogel {@link http://www.kubik-rubik.de}
 * @version		1.6-2
 * @date 		Created on 22-Mar-2011
 * @link		Project Site {@link http://joomla-extensions.kubik-rubik.de/ecc-easycalccheck-plus}
 *
 *	@license GNU/GPL
 *	This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');

/**
 * EasyCalcCheck PLUS
 * System Plugin
 *
 * @package		EasyCalcCheckPlus
 * @subpackage	Plugin
 */
class plgSystemEasyCalcCheckPlus extends JPlugin
{
	/**
	* Constructor
	*
	* @access      protected
	* @param       object  $subject The object to observe
	* @param       array   $config  An array that holds the plugin configuration
	*/
	function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config);

		// Load language from administrator folder
		$this->loadLanguage('', JPATH_ADMINISTRATOR);
	}

	/**
	* Search form fields and set protection mechanisms
	*
	* @return void
	*/
	public function onAfterRender()
	{
		// Only in frontend
		$app = JFactory::getApplication();

		if ($app->isAdmin())
		{
			return;
		}

		$option = JRequest::getWord('option');
		$view = JRequest::getWord('view');
		$page = JRequest::getCmd('page');
		$task = JRequest::getWord('task');
		$layout = JRequest::getWord('layout');
		$func = JRequest::getWord('func');
		$do = JRequest::getWord('do');

		switch ($option)
		{
			case 'com_contact':
				if (!$this->params->get('contact')) { return; }
				if ($view != 'contact') { return; };
			break;

			case 'com_users':
				if (!$this->params->get('user_reg')) { return; }
				if ($view != 'registration' AND $view != 'reset' AND $view != 'remind') { return; };
				if ($layout == 'confirm' OR $layout == 'complete') { return; };
			break;
			
			// Easybook Reloaded - tested with version 3.0.3 - 1.6-2
			case 'com_easybookreloaded':
				if (!$this->params->get('easybookreloaded')) { return; }
				if ($task != 'add') { return; };
				$_SESSION["easybookreloaded"] = 0;
			break;
			
			
			// Phoca Guestbook - tested with version 2.0.0RC - 1.6-2
			case 'com_phocaguestbook':
				if (!$this->params->get('phocaguestbook')) { return; }
				if ($view != 'guestbook') { return; };
			break;

			default:
				return;
			break;
			
			// Community Builder - tested with version 1.4.0 - 1.6-2
			case 'com_comprofiler':
				if (!$this->params->get('communitybuilder')) { return; }
				if ($task != 'registers' AND $task != 'lostpassword') { return; };
			break;
		}

		$this->loadLanguage('', JPATH_ADMINISTRATOR); // Google Translator Fix
		$body = JResponse::getBody(); // Read in content of the output
		
		// Fill in form input values if the check failed
		if ($this->params->get('autofill_values'))
		{
			require_once(dirname(__FILE__).DS.'easycalccheckplus'.DS.'autofill.php');
		}
		
		// Hidden field
		if ($this->params->get('type_hidden'))
		{
			// Random variable for display of the hidden field
			$lsrandom = mt_rand(1,5);
			// Line width for obfuscation
			$input_size = 30;
			// When using layout overrides the output could vary. Search string should be adjusted if necessary!
			if ($option == 'com_contact' AND $view == 'contact')
			{
				if ($lsrandom == 1)
				{
					$searchString = '<label for="contact-formname">';
				}
				elseif ($lsrandom == 2)
				{
					$searchString = '<label id="contact-emailmsg" for="contact-email">';
				}
				elseif ($lsrandom == 3)
				{
					$searchString = '<label for="contact-subject">';
				}
				elseif ($lsrandom == 4)
				{
					$searchString = '<label id="contact-textmsg" for="contact-text">';
				}
				elseif ($lsrandom == 5)
				{
					$searchString = '<label for="contact-email-copy">';
				}
			}
			elseif ($option == 'com_users' AND $view == 'registration')
			{
				$lsrandom = mt_rand(1,6);
				
				if ($lsrandom == 1)
				{
					$searchString = '<label id="jform_name-lbl"';
				}
				elseif ($lsrandom == 2)
				{
					$searchString = '<label id="jform_username-lbl"';
				}
				elseif ($lsrandom == 3)
				{
					$searchString = '<label id="jform_password1-lbl"';
				}
				elseif ($lsrandom == 4)
				{
					$searchString = '<label id="jform_password2-lbl"';
				}
				elseif ($lsrandom == 5)
				{
					$searchString = '<label id="jform_email1-lbl"';
				}
				elseif ($lsrandom == 6)
				{
					$searchString = '<label id="jform_email2-lbl"';
				}
			}
			elseif ($option == 'com_users' AND ($view == 'reset' OR $view == 'remind'))
			{
				$searchString = '<label id="jform_email-lbl"';
			}
			elseif ($option == 'com_easybookreloaded') // Easybook Reloaded
			{
				$lsrandom = mt_rand(1,3);

				if ($lsrandom == 1)
				{
					$searchString = '<input type=\'text\' name=\'gbname\' id=\'gbname\'';
				}
				elseif ($lsrandom == 2)
				{
					$searchString = '<input type=\'text\' name=\'gbmail\' id=\'gbmail\'';
				}
				elseif ($lsrandom == 3)
				{
					$searchString = '<textarea name=\'gbtext\' id=\'gbtext\'';
				}
			}
			elseif ($option == 'com_phocaguestbook') // Phoca Guestbook
			{
				$lsrandom = mt_rand(1,4);

				if ($lsrandom == 1)
				{
					$searchString = '<input type="text" name="title"';
				}
				elseif ($lsrandom == 2)
				{
					$searchString = '<input type="text" name="pgusername"';
				}
				elseif ($lsrandom == 3)
				{
					$searchString = '<input type="text" name="email"';
				}
				elseif ($lsrandom == 4)
				{
					$searchString = '<textarea id="pgbcontent" name="pgbcontent"';
				}
			}
			elseif ($option == 'com_comprofiler' AND $task == 'registers')
			{
				if ($lsrandom == 1)
				{
					$searchString = '<label for="name"';
				}
				elseif ($lsrandom == 2)
				{
					$searchString = '<label for="username"';
				}
				elseif ($lsrandom == 3)
				{
					$searchString = '<label for="email"';
				}
				elseif ($lsrandom == 4)
				{
					$searchString = '<label for="password"';
				}
				elseif ($lsrandom == 5)
				{
					$searchString = '<label for="password__verify"';
				}
			}
			elseif ($option == 'com_comprofiler' AND $task == 'lostpassword')
			{
				$searchString = '<label for="checkemail">';
			}

			// Generate random variable
			$_SESSION["hidden_field"] = $this->random();
			$_SESSION["hidden_field_label"] = $this->random();

			$addString = '<label for="'.$_SESSION["hidden_field_label"].'"></label><input type="text" id="'.$_SESSION["hidden_field_label"].'" name="'.$_SESSION["hidden_field"].'" size="'.$input_size.'" class="inputbox '.$_SESSION["hidden_class"].'" />';

			if (isset($searchString))
			{
				$body = str_replace($searchString, $addString.$searchString, $body);
				JResponse::setBody($body);
			}
		}

		// Encode fields - only in core components
		if ($this->params->get('encode'))
		{
			if ($option == 'com_contact' OR $option == 'com_users')
			{
				$session = JFactory::getSession();

				// Set random variable
				$random = $this->random();
				$random2 = $this->random();
				$random3 = $this->random();
				$random4 = $this->random();
				$random5 = $this->random();
				$random6 = $this->random();

				if ($option == 'com_contact')
				{
					$session->set('name', $random, 'easycalccheck');
					$session->set('email', $random2, 'easycalccheck');
					$session->set('subject', $random3, 'easycalccheck');
					$session->set('text', $random4, 'easycalccheck');
					$session->set('email_copy', $random5, 'easycalccheck');

					$name_old = array ('name="name"' , 'name="email"' , 'name="subject"' , 'name="text"' , 'name="email_copy"');
					$name_new = array ('name="'.$random.'"' ,  'name="'.$random2.'"' ,  'name="'.$random3.'"' ,  'name="'.$random4.'"' ,  'name="'.$random5.'"');

					$id_old = array ('class="inputbox',  'contact-email-copy', 'for="contact-email"', 'id="contact-email"', 'id="contact-emailmsg"', 'contact-textmsg', 'contact-formname', 'contact-subject', 'contact-textmsg', 'contact-text');
					$id_new = array ('class="inputbox '.$this->random().'',  $this->random() , 'for="'.$this->random().'"', 'id="'.$this->random().'"', 'id="'.$this->random().'"', $this->random(), $this->random(), $this->random(), $this->random(), $this->random());

					$body = str_replace($name_old, $name_new , $body);
					$body = str_replace($id_old, $id_new , $body);
				}
				elseif ($option == 'com_users' AND $view == 'registration')
				{
					$session->set('jform[name]', $random, 'easycalccheck');
					$session->set('jform[username]', $random2, 'easycalccheck');
					$session->set('jform[email1]', $random3, 'easycalccheck');
					$session->set('jform[email2]', $random4, 'easycalccheck');
					$session->set('jform[password1]', $random5, 'easycalccheck');
					$session->set('jform[password2]', $random6, 'easycalccheck');

					$name_old = array ('name="jform[name]"' ,'name="jform[username]"' ,'name="jform[email1]"' ,'name="jform[email2]"' ,'name="jform[password1]"' ,'name="jform[password2]"');
					$name_new = array ('name="'.$random.'"' ,  'name="'.$random2.'"' ,'name="'.$random3.'"' ,  'name="'.$random4.'"' ,  'name="'.$random5.'"' ,  'name="'.$random6.'"');

					$id_old = array ('jform_name' , 'jform_name-lbl' , 'jform_username' , 'jform_username-lbl' , 'jform_password1' , '"jform_password1-lbl"' , 'jform_password2' , 'jform_password2-lbl' , '"jform_email1"' , '"jform_email1-lbl"' , '"jform_email2"' , 'jform_email2-lbl');
					$id_new = array ($this->random(),  $this->random(), $this->random(), $this->random(), $this->random(), $this->random(),  $this->random(), $this->random(), $this->random(), $this->random(), $this->random(), $this->random());

					$body = str_replace($name_old, $name_new , $body);
					$body = str_replace($id_old, $id_new , $body);
				}

				JResponse::setBody($body);
			}
		}

		// Calc check
		if ($this->params->get('type_calc') OR ($this->params->get('recaptcha')) OR ($this->params->get('question')))
		{
			if ($option == 'com_easybookreloaded')
			{
				if ($task == 'add')
				{
					$muster = '@(<p id="easysubmit">)@s';

					if (preg_match($muster, $body, $matches))
					{
						$searchString = $matches[0];
					}
				}
			}
			elseif ($option == 'com_phocaguestbook')
			{
				if ($view == 'guestbook')
				{
					$muster = '@(<input type="submit" name="save" value=".+" />)@';
					if (preg_match($muster, $body, $matches))
					{
						$searchString = $matches[0];
					}
				}
			}
			elseif ($option == 'com_comprofiler')
			{
				if ($task == 'registers')
				{
					$muster = '@(<input type="submit" value=".+" class="button" />)@';
					if (preg_match($muster, $body, $matches))
					{
						$searchString = $matches[0];
					}
				}
				elseif ($task == 'lostpassword')
				{
					$muster = '@(<input type="submit" class="button" id="cbsendnewuspass" value=".+" />)@';
					if (preg_match($muster, $body, $matches))
					{
						$searchString = $matches[0];
					}
				}
			}
			else
			{
				if ($view == 'reset' OR $view == 'remind') // User - Password or Username
				{
					$searchString = '<button type="submit">';
				}
				else // User and Contact forms
				{
					if ($option == 'com_contact')
					{
						// Without overrides
						$pattern = '@(<button class="button validate" type="submit">)@';
						if (preg_match($pattern, $body, $matches))
						{
							$searchString = $matches[0];
						}
						else // With overrides
						{
							$pattern = '@<form[^>]*id="emailForm".*>.*(<[^>]*type="submit".*>).*</form>@isU';
							if (preg_match($pattern, $body, $matches))
							{
								$searchString = $matches[1];
							}
						}
					}
					elseif($option == 'com_users')
					{
						// Without overrides
						$pattern = '@(<button type="submit" class="validate">)@';
						if (preg_match($pattern, $body, $matches))
						{
							$searchString = $matches[0];
						}
						else // With overrides
						{
							$pattern = '@<form[^>]*id="member-registration".*>.*(<[^>]*type="submit".*>).*</form>@isU';
							if (preg_match($pattern, $body, $matches))
							{
								$searchString = $matches[1];
							}
						}
					}
				}
			}

			if ($this->params->get('type_calc'))
			{
				$_SESSION["spamcheck"] = $this->random();
				$_SESSION["rot13"] = mt_rand(0,1);

				// Determine operator
				if ($this->params->get('operator') == 2)
				{
					$tcalc = mt_rand(1,2);
				}
				elseif ($this->params->get('operator') == 1)
				{
					$tcalc = 2;
				}
				else
				{
					$tcalc = 1;
				}

				// Determine max. operand
				$max_value = $this->params->get('max_value', 20);

				if (($this->params->get('negativ') == 0) AND ($tcalc == 2))
				{
					$spamCheckNr1 = mt_rand($max_value / 2, $max_value);
					$spamCheckNr2 = mt_rand(1, $max_value / 2);
					if ($this->params->get('operand') == 3)
					{
						$spamCheckNr3 = mt_rand(0, $spamCheckNr1 - $spamCheckNr2);
					}
				}
				else
				{
					$spamCheckNr1 = mt_rand(1, $max_value);
					$spamCheckNr2 = mt_rand(1, $max_value);
					if ($this->params->get('operand') == 3)
					{
						$spamCheckNr3 = mt_rand(0, $max_value);
					}
				}

				// Save the result as a session variable
				$addString = '';

				if ($tcalc == 1) // Addition
				{
					if ($_SESSION["rot13"] == 1) // ROT13 coding
					{
						if ($this->params->get('operand') == 2)
						{
							$_SESSION["spamcheckresult"]  = str_rot13(base64_encode($spamCheckNr1 + $spamCheckNr2));
						}
						elseif ($this->params->get('operand') == 3)
						{
							$_SESSION["spamcheckresult"] = str_rot13(base64_encode($spamCheckNr1 + $spamCheckNr2 + $spamCheckNr3));
						}
					}
					else
					{
						if ($this->params->get('operand') == 2)
						{
							$_SESSION["spamcheckresult"] = base64_encode($spamCheckNr1 + $spamCheckNr2);
						}
						elseif ($this->params->get('operand') == 3)
						{
							$_SESSION["spamcheckresult"] = base64_encode($spamCheckNr1 + $spamCheckNr2 + $spamCheckNr3);
						}
					}
				}
				elseif ($tcalc == 2) // Subtraction
				{
					if ($_SESSION["rot13"] == 1)
					{
						if ($this->params->get('operand') == 2)
						{
							$_SESSION["spamcheckresult"] = str_rot13(base64_encode($spamCheckNr1 - $spamCheckNr2));
						}
						elseif ($this->params->get('operand') == 3)
						{
							$_SESSION["spamcheckresult"] = str_rot13(base64_encode($spamCheckNr1 - $spamCheckNr2 - $spamCheckNr3));
						}
					}
					else
					{
						if ($this->params->get('operand') == 2)
						{
							$_SESSION["spamcheckresult"] = base64_encode($spamCheckNr1 - $spamCheckNr2);
						}
						elseif ($this->params->get('operand') == 3)
						{
							$_SESSION["spamcheckresult"] = base64_encode($spamCheckNr1 - $spamCheckNr2 - $spamCheckNr3);
						}
					}
				}

				// Show the calc check
				if ($option == 'com_easybookreloaded')
				{
					$addString .= '<div style="padding-left: 50px;"><label for="'.$_SESSION["spamcheck"].'">';
				}
				else
				{
					$addString .= '<div><label for="'.$_SESSION["spamcheck"].'">';
				}

				$addString .= JText::_('SPAMCHECK').': ';
				if ($tcalc == 1)
				{
					if ($this->params->get('converttostring'))
					{
						if ($this->params->get('operand') == 2)
						{
							$addString .= $this->converttostring($spamCheckNr1).' '.JText::_('PLUS').' '.$this->converttostring($spamCheckNr2).' '.JText::_('EQUALS').' ';
						}
						elseif ($this->params->get('operand') == 3)
						{
							$addString .= $this->converttostring($spamCheckNr1).' '.JText::_('PLUS').' '.$this->converttostring($spamCheckNr2).' '.JText::_('PLUS').' '.$this->converttostring($spamCheckNr3).' '.JText::_('EQUALS').' ';
						}
					}
					else
					{
						if ($this->params->get('operand') == 2)
						{
							$addString .= $spamCheckNr1.' '.JText::_('PLUS').' '.$spamCheckNr2.' '.JText::_('EQUALS').' ';
						}
						elseif ($this->params->get('operand') == 3)
						{
							$addString .= $spamCheckNr1.' '.JText::_('PLUS').' '.$spamCheckNr2.' '.JText::_('PLUS').' '.$spamCheckNr3.' '.JText::_('EQUALS').' ';
						}
					}
				}
				elseif ($tcalc == 2)
				{
					if ($this->params->get('converttostring'))
					{
						if ($this->params->get('operand') == 2)
						{
							$addString .= $this->converttostring($spamCheckNr1).' '.JText::_('MINUS').' '.$this->converttostring($spamCheckNr2).' '.JText::_('EQUALS').' ';
						}
						elseif ($this->params->get('operand') == 3)
						{
							$addString .= $this->converttostring($spamCheckNr1).' '.JText::_('MINUS').' '.$this->converttostring($spamCheckNr2).' '.JText::_('MINUS').' '.$this->converttostring($spamCheckNr3).' '.JText::_('EQUALS').' ';
						}
					}
					else
					{
						if ($this->params->get('operand') == 2)
						{
							$addString .= $spamCheckNr1.' '.JText::_('MINUS').' '.$spamCheckNr2.' '.JText::_('EQUALS').' ';
						}
						elseif ($this->params->get('operand') == 3)
						{
							$addString .= $spamCheckNr1.' '.JText::_('MINUS').' '.$spamCheckNr2.' '.JText::_('MINUS').' '.$spamCheckNr3.' '.JText::_('EQUALS').' ';
						}
					}
				}
				$addString .= '</label>';
				$addString .= '<input type="text" name="'.$_SESSION["spamcheck"].'" id="'.$_SESSION["spamcheck"].'" size="3" class="inputbox '.$this->random().'" value="" /> *';
				$addString .= '</div>';

				// Show warnings
				if ($this->params->get('warn_ref') AND !$this->params->get('autofill_values'))
				{
					if ($option == 'com_easybookreloaded')
					{
						$addString .= '<p style="padding-left: 50px;"><img src="'.JURI::root().'plugins/system/easycalccheckplus/easycalccheckplus/warning.png" alt="'.JText::_('WARNING').'" /> ';
					}
					else
					{
						$addString .= '<p><img src="'.JURI::root().'plugins/system/easycalccheckplus/easycalccheckplus/warning.png" alt="'.JText::_('WARNING').'" /> ';
					}
					$addString .= '<strong>'.JText::_('WARNING').'</strong><br /><small>'.JText::_('WARNINGDESC').'</small>';
					if ($this->params->get('converttostring'))
					{
						$addString .= '<br /><small>'.JText::_('CONVERTWARNING').'</small><br />';
					}
					$addString .= '</p>';
				}
				elseif ($this->params->get('converttostring'))
				{
					if ($option == 'com_easybookreloaded')
					{
						$addString .= '<p style="padding-left: 50px;"><small>'.JText::_('CONVERTWARNING').'</small></p>';
					}
					else
					{
						$addString .= '<p><small>'.JText::_('CONVERTWARNING').'</small></p>';
					}
				}

				if (isset($searchString))
				{
					$body = str_replace($searchString, $addString.$searchString, $body);
					JResponse::setBody($body);
				}
			}

			// ReCaptcha
			if ($this->params->get('recaptcha') AND $this->params->get('recaptcha_publickey') AND $this->params->get('recaptcha_privatekey'))
			{
				require_once(dirname(__FILE__).DS.'easycalccheckplus'.DS.'recaptchalib.php');
				$publickey = $this->params->get('recaptcha_publickey');

				$addString = recaptcha_get_html($publickey).'<br />';

				if (isset($searchString))
				{
					$body = str_replace($searchString, $addString.$searchString, $body);
					JResponse::setBody($body);
				}

			}

			// Own Question
			if ($this->params->get('question') AND $this->params->get('question_q') AND $this->params->get('question_a'))
			{
				$_SESSION["question"] = $this->random();
				
				$size = strlen($this->params->get('question_a')) +  mt_rand(0,2);

				if ($option == 'com_easybookreloaded')
				{
					$addString = '<p style="padding-left: 50px;">'.$this->params->get('question_q').' <input type="text" name="'.$_SESSION["question"].'" id="'.$_SESSION["question"].'" size="'.$size.'" class="inputbox '.$this->random().'" value="" /> *</p>';
				}
				else
				{
					$addString = '<p>'.$this->params->get('question_q').' <input type="text" name="'.$_SESSION["question"].'" id="'.$_SESSION["question"].'" size="'.$size.'" class="inputbox '.$this->random().'" value="" /> *</p>';
				}

				if (isset($searchString))
				{
					$body = str_replace($searchString, $addString.$searchString, $body);
					JResponse::setBody($body);
				}
			}
		}

		// Time Lock
		if ($this->params->get('type_time'))
		{
			$_SESSION["time"] = time();
		}

		// Get IP Address
		$_SESSION["ip"] = getenv('REMOTE_ADDR');

		// No Quick Reply for guests - Entry only through normal form
		// CODE...

		// Set session variable for error output - Phoca Guestbook / Easybook Reloaded
		if ($option == 'com_phocaguestbook')
		{
			$_SESSION["phocaguestbook"] = 0;
		}
		if ($option == 'com_easybookreloaded')
		{
			$_SESSION["easybookreloaded"] = 0;
		}

		return;
	} // End of function onAfterRender

	/**
	*
	* Reset all input fields so the components can work with them
	* Set the css assignment in the header - important for seo
	*
	*/
	function onAfterRoute()
	{
		$app = JFactory::getApplication();
		$option = JRequest::getWord('option');
		$task = JRequest::getCmd('task');
		$format = JRequest::getWord('format');
		$page = JRequest::getCmd('page');
		$view = JRequest::getWord('view');
		$func = JRequest::getWord('func');

		// Only in frontend, don't use for VCARD or PDF creation - (no addCustomTag)
		if (($app->isAdmin()) OR ($task == 'vcard') OR ($format == 'pdf'))
		{
			return;
		}

		if ($this->params->get('type_hidden') OR ($this->params->get('easybookreloaded') AND $this->params->get('recaptcha') AND $option == "com_easybookreloaded"))
		{
			if (($this->params->get('contact') AND $option == "com_contact" AND $view == 'contact') OR ($this->params->get('user_reg') AND $option == "com_users") OR ($this->params->get('easybookreloaded') AND $option == "com_easybookreloaded") OR ($this->params->get('phocaguestbook') AND $option == "com_phocaguestbook") OR ($this->params->get('communitybuilder') AND $option == 'com_comprofiler' AND ($task == 'registers' OR $task == 'lostpassword')))
			{
				$head = array();
				if ($this->params->get('type_hidden'))
				{
					$_SESSION["hidden_class"] = $this->random();
					$head[] = '<style type="text/css">.'.$_SESSION["hidden_class"].' {display: none;}</style>';
				}
				if ($this->params->get('easybookreloaded') AND $this->params->get('recaptcha') AND $option == "com_easybookreloaded")
				{
					$head[] = '<style type="text/css">div#recaptcha_area{padding-left: 50px !important;}</style>';
				}

				$head = "\n".implode("\n", $head)."\n";
				$document = JFactory::getDocument();
				$document->addCustomTag($head);
			}
		}

		// Reset all input fields
		if ($this->params->get('encode'))
		{
			$session = JFactory::getSession();
			if ($this->params->get('contact') AND ($option == 'com_contact') AND ($view == 'contact'))
			{
				$name = $session->get('name', null, 'easycalccheck');
				$email = $session->get('email', null, 'easycalccheck');
				$subject = $session->get('subject', null, 'easycalccheck');
				$text = $session->get('text', null, 'easycalccheck');
				$email_copy = $session->get('email_copy', null, 'easycalccheck');

				$name_value = JRequest::getString($name);
				$email_value = JRequest::getString($email);
				$subject_value = JRequest::getString($subject);
				$text_value = JRequest::getString($text);
				$email_copy_value = JRequest::getString($email_copy);

				JRequest::setVar('name', $name_value);
				JRequest::setVar('email', $email_value);
				JRequest::setVar('subject', $subject_value);
				JRequest::setVar('text', $text_value);
				JRequest::setVar('email_copy', $email_copy_value);

				$session->clear('name','easycalccheck');
				$session->clear('email','easycalccheck');
				$session->clear('subject','easycalccheck');
				$session->clear('text','easycalccheck');
				$session->clear('email_copy','easycalccheck');
			}
			elseif ($this->params->get('user_reg') AND ($option == 'com_users') AND ($task == 'registration.register'))
			{
				$name = $session->get('jform[name]', null, 'easycalccheck');
				$username = $session->get('jform[username]', null, 'easycalccheck');
				$password1 = $session->get('jform[password1]', null, 'easycalccheck');
				$password2 = $session->get('jform[password2]', null, 'easycalccheck');				
				$email1 = $session->get('jform[email1]', null, 'easycalccheck');
				$email2 = $session->get('jform[email2]', null, 'easycalccheck');
				
				$jform = array();
				$jform['jform']['name'] = JRequest::getString($name);
				$jform['jform']['username'] = JRequest::getString($username);
				$jform['jform']['password1'] = JRequest::getString($password1);
				$jform['jform']['password2'] = JRequest::getString($password2);
				$jform['jform']['email1'] = JRequest::getString($email1);
				$jform['jform']['email2'] = JRequest::getString($email2);

				JRequest::set($jform, 'post', true);

				$session->clear('jform[name]','easycalccheck');
				$session->clear('jform[username]','easycalccheck');
				$session->clear('jform[password1]','easycalccheck');
				$session->clear('jform[password2]','easycalccheck');
				$session->clear('jform[email1]','easycalccheck');
				$session->clear('jform[email2]','easycalccheck');
			}
		}

		// Save entered values in session for autofill
		if ($this->params->get('autofill_values'))
		{
			$request = JRequest::get();
			$session = JFactory::getSession();

			if ($option == 'com_contact')
			{
				if (!empty($request['name']))
				{
					$session->set('autofill_name', $request['name'], 'easycalccheck');
				}
				if (!empty($request['email']))
				{
					$session->set('autofill_email', $request['email'], 'easycalccheck');
				}
				if (!empty($request['subject']))
				{
					$session->set('autofill_subject', $request['subject'], 'easycalccheck');
				}
				if (!empty($request['text']))
				{
					$session->set('autofill_text', $request['text'], 'easycalccheck');
				}

			}
			elseif ($option == 'com_users')
			{
				if (!empty($request['jform']['name']))
				{
					$session->set('autofill_name', $request['jform']['name'], 'easycalccheck');
				}
				if (!empty($request['jform']['username']))
				{
					$session->set('autofill_username', $request['jform']['username'], 'easycalccheck');
				}
				if (!empty($request['jform']['email1']))
				{
					$session->set('autofill_email1', $request['jform']['email1'], 'easycalccheck');
				}
				if (!empty($request['jform']['email2']))
				{
					$session->set('autofill_email2', $request['jform']['email2'], 'easycalccheck');
				}
			}
			elseif ($option == 'com_easybookreloaded')
			{
				if (!empty($request['gbname']))
				{
					$session->set('autofill_gbname', $request['gbname'], 'easycalccheck');
				}
				if (!empty($request['gbmail']))
				{
					$session->set('autofill_gbmail', $request['gbmail'], 'easycalccheck');
				}
				if (!empty($request['gbpage']))
				{
					$session->set('autofill_gbpage', $request['gbpage'], 'easycalccheck');
				}
				if (!empty($request['gbloca']))
				{
					$session->set('autofill_gbloca', $request['gbloca'], 'easycalccheck');
				}
				if (!empty($request['gbicq']))
				{
					$session->set('autofill_gbicq', $request['gbicq'], 'easycalccheck');
				}
				if (!empty($request['gbaim']))
				{
					$session->set('autofill_gbaim', $request['gbaim'], 'easycalccheck');
				}
				if (!empty($request['gbmsn']))
				{
					$session->set('autofill_gbmsn', $request['gbmsn'], 'easycalccheck');
				}
				if (!empty($request['gbyah']))
				{
					$session->set('autofill_gbyah', $request['gbyah'], 'easycalccheck');
				}
				if (!empty($request['gbskype']))
				{
					$session->set('autofill_gbskype', $request['gbskype'], 'easycalccheck');
				}
				if (!empty($request['gbvote']))
				{
					$session->set('autofill_gbvote', $request['gbvote'], 'easycalccheck');
				}
				if (!empty($request['gbtext']))
				{
					$session->set('autofill_gbtext', $request['gbtext'], 'easycalccheck');
				}
			}
			elseif ($option == 'com_phocaguestbook')
			{
				if (!empty($request['title']))
				{
					$session->set('autofill_title', $request['title'], 'easycalccheck');
				}
				if (!empty($request['pgusername']))
				{
					$session->set('autofill_pgusername', $request['pgusername'], 'easycalccheck');
				}
				if (!empty($request['email']))
				{
					$session->set('autofill_email', $request['email'], 'easycalccheck');
				}
				if (!empty($request['pgbcontent']))
				{
					$session->set('autofill_pgbcontent', $request['pgbcontent'], 'easycalccheck');
				}
			}
			elseif ($option == 'com_comprofiler')
			{
				if (!empty($request['name']))
				{
					$session->set('autofill_name', $request['name'], 'easycalccheck');
				}
				if (!empty($request['firstname']))
				{
					$session->set('autofill_firstname', $request['firstname'], 'easycalccheck');
				}
				if (!empty($request['middlename']))
				{
					$session->set('autofill_middlename', $request['middlename'], 'easycalccheck');
				}
				if (!empty($request['lastname']))
				{
					$session->set('autofill_lastname', $request['lastname'], 'easycalccheck');
				}
				if (!empty($request['email']))
				{
					$session->set('autofill_email', $request['email'], 'easycalccheck');
				}
				if (!empty($request['username']))
				{
					$session->set('autofill_username', $request['username'], 'easycalccheck');
				}
				if (!empty($request['company']))
				{
					$session->set('autofill_company', $request['company'], 'easycalccheck');
				}
				if (!empty($request['city']))
				{
					$session->set('autofill_city', $request['city'], 'easycalccheck');
				}
				if (!empty($request['state']))
				{
					$session->set('autofill_state', $request['state'], 'easycalccheck');
				}
				if (!empty($request['zipcode']))
				{
					$session->set('autofill_zipcode', $request['zipcode'], 'easycalccheck');
				}
				if (!empty($request['country']))
				{
					$session->set('autofill_country', $request['country'], 'easycalccheck');
				}
				if (!empty($request['address']))
				{
					$session->set('autofill_address', $request['address'], 'easycalccheck');
				}
				if (!empty($request['phone']))
				{
					$session->set('autofill_phone', $request['phone'], 'easycalccheck');
				}
				if (!empty($request['fax']))
				{
					$session->set('autofill_fax', $request['fax'], 'easycalccheck');
				}
			}
		}
		
		// Validation - Password and Username
		if ($this->params->get('user_reg'))
		{
			if ($option == 'com_users' AND $task == 'reset.request')
			{	
				if (!$this->performChecks())
				{
					$returnURI = JURI::current().'?option=com_users&view=reset&essp_err=check_failed';
					$this->redirect($returnURI);
				}
			}
			elseif ($option == 'com_users' AND $task == 'remind.remind')
			{
				if (!$this->performChecks())
				{
					$returnURI = JURI::current().'?option=com_users&view=remind&essp_err=check_failed';
					$this->redirect($returnURI);
				}
			}
		}
		
		if ($this->params->get('easybookreloaded'))
		{
			if ($option == 'com_easybookreloaded' AND $task == 'save')
			{
				$Itemid = JRequest::getCmd('Itemid');

				if (!$this->performChecks())
				{
					$_SESSION["easybookreloaded"] = 1;
					$returnURI = JURI::current().'?option=com_easybookreloaded&controller=entry&task=add&Itemid='.$Itemid.'&essp_err=check_failed';
					$this->redirect($returnURI);
				}
			}
		}
		
		if ($this->params->get('phocaguestbook'))
		{
			if ($option == 'com_phocaguestbook' AND $task == 'submit')
			{
				$id = JRequest::getCmd('id');
				$Itemid = JRequest::getCmd('Itemid');

				if (!$this->performChecks())
				{
					$_SESSION["phocaguestbook"] = 1;
					$returnURI = JURI::current().'?option=com_phocaguestbook&view=guestbook&id='.$id.'&Itemid='.$Itemid.'&essp_err=check_failed';
					$this->redirect($returnURI);
				}
			}
		}
		
		// Community Builder - new password
		if ($this->params->get('communitybuilder'))
		{
			if ($option == 'com_comprofiler' AND $task == 'sendNewPass')
			{
				if (!$this->performChecks())
				{
					$returnURI = JURI::current().'?option=com_comprofiler&task=lostpassword&essp_err=check_failed';
					$this->redirect($returnURI);
				}
			}
		}
	} // End of function onAfterRoute

	/**
	 * Redirectet with PHP / JS - throw error message
	 *
	 * @return void
	 */
	function onAfterInitialise()
	{
		$option = JRequest::getWord('option');
		$task = JRequest::getCmd('task');

		if (JRequest::getCmd('essp_err', '', 'get') == 'check_failed')
		{
			if (($option == 'com_phocaguestbook' AND $_SESSION["phocaguestbook"] == 0) OR ($option == 'com_easybookreloaded' AND $_SESSION["easybookreloaded"] == 0))
			{
				// No message - message is raised by components
			}
			else
			{
				JError::raiseWarning(100, JText::_('YOUHAVENOTRESOLVEDOURSPAMCHECK'));
			}
		}
		
		// Clean Cache
		$cache = JFactory::getCache($option);
		$cache->clean();		
		$cache->remove($cache->makeId(), 'page');

		// Bot-Trap
		// Further informations: http://www.bot-trap.de
		// File has to be named page.restrictor.php and should be saved in plugins/system/bottrap
		if ($this->params->get('bottrap'))
		{
			$app = JFactory::getApplication();

			if ($app->isAdmin())
			{
				$path = '../plugins/system/easycalccheckplus/bottrap/';
			}
			else
			{
				$path = 'plugins/system/easycalccheckplus/bottrap/';
			}

			if (file_exists($path.'page.restrictor.php'))
			{
				if ($this->params->get('btWhitelistIP'))
				{
					$btWhitelistIP = str_replace(',', '|', $this->params->get('btWhitelistIP'));
					define('PRES_WHITELIST_IP', $btWhitelistIP);
				}
				if ($this->params->get('btWhitelistIPRange'))
				{
					$btWhitelistIPRange = str_replace(',', '|', $this->params->get('btWhitelistIPRange'));
					define('PRES_WHITELIST_IPR', $btWhitelistIPRange);
				}
				if ($this->params->get('btWhitelistUA'))
				{
					$btWhitelistUA = str_replace(',', '|', $this->params->get('btWhitelistUA'));
					define('PRES_WHITELIST_UA', $btWhitelistUA);
				}
				if ($this->params->get('btBlacklistIP'))
				{
					$btBlacklistIP = str_replace(',', '|', $this->params->get('btBlacklistIP'));
					define('PRES_BLACKLIST_IP', $btBlacklistIP);
				}
				if ($this->params->get('btBlacklistIPRange'))
				{
					$btBlacklistIPRange = str_replace(',', '|', $this->params->get('btBlacklistIPRange'));
					define('PRES_BLACKLIST_IPR', $btBlacklistIPRange);
				}
				if ($this->params->get('btBlacklistUA'))
				{
					$btBlacklistUA = str_replace(',', '|', $this->params->get('btBlacklistUA'));
					define('PRES_BLACKLIST_UA', $btBlacklistUA);
				}
				include_once($path.'page.restrictor.php');
			}
			else
			{
				JError::raiseWarning(100, JText::_('ERRORBOTTRAP'));
			}
		}

		// Credit: Marco's SQL Injection Plugin
		// Further informations: http://www.mmleoni.net/sql-iniection-lfi-protection-plugin-for-joomla
		if ($this->params->get('sqlinjection-lfi'))
		{
			$mainframe = JFactory::getApplication();
			$p_dbprefix = $mainframe->getCfg('dbprefix');
			$p_errorCode = 500;
			$p_errorMsg = 'Internal Server Error';
			$p_strictLFI = 1;
			$p_levelLFI = 1;
			$p_nameSpaces = 'GET,POST,REQUEST';
			$wr = array();

			foreach (explode(',', $p_nameSpaces) as $nsp)
			{
				switch ($nsp)
				{
					case 'GET':
						$nameSpace =& $_GET;
						break;
					case 'POST':
						$nameSpace =& $_POST;
						break;
					case 'REQUEST':
						$nameSpace =& $_REQUEST;
						break;
				}

				foreach($nameSpace as $k => &$v)
				{
					if(is_numeric($v)) continue;
					if(is_array($v)) continue;
					/* SQL injection */
					// strip /* comments */
					$a = preg_replace('!/\*.*?\*/!s', ' ', $v);
					/* union select ... jos_users */
					if (preg_match('/UNION(?:\s+ALL)?\s+SELECT/i', $a))
					{
						JError::raiseError($p_errorCode, $p_errorMsg);
						return;
					}
					/* Table names */
					$ta = array ('/\s`?+(#__)/', '/\s+`?(jos_)/i', "/\s+`?({$p_dbprefix}_)/i");
					foreach ($ta as $t)
					{
						if (preg_match($t, $v))
						{
							JError::raiseError($p_errorCode, $p_errorMsg);
							return;
						}
					}
					/* LFI */
					if ($p_strictLFI)
					{
						if (!in_array($k, array('controller', 'view', 'model', 'template'))) continue;
					}
					$recurse = str_repeat('\.\.\/', $p_levelLFI+1);
					$i=0;
					while (preg_match("/$recurse/", $v))
					{
						JError::raiseError($p_errorCode, $p_errorMsg);
						return;
						$i++;
					}
					unset($v);
				}
			}
		}

		// Backend protection
		// Inspired by the plugin Backend Token - http://extensions.joomla.org/extensions/access-a-security/site-security/login-protection/13919
		if ($this->params->get('backendprotection'))
		{
			$app = JFactory::getApplication();
			if ($app->isAdmin())
			{
				$user = JFactory::getUser();
				if ($user->guest)
				{
					$session = JFactory::getSession();

					$token = $this->params->get('token');
					$request = JRequest::get();
					$tokensession = $session->get('token', null, 'easycalccheck');
					
					if (!isset($request['token']))
					{
						$request['token'] = 0;
					}

					if (!isset($tokensession))
					{
						$tokensession = $session->set('token', 0, 'easycalccheck');
					}
					if (utf8_encode($request['token']) == $token) // Conversion to UTF8 (german umlaute)
					{
						$tokensession = $session->set('token', 1, 'easycalccheck');
					}
					elseif (utf8_encode($request['token']) != $token)
					{
						$url = $this->params->get('urlfalsetoken');
						if (empty($url))
						{
							$url = JURI::root();
						}
						if ($tokensession != 1)
						{
							$tokensession = $session->clear('token','easycalccheck');
							$this->redirect($url);
						}
					}
				}
			}
		}
	} // Ende of function onAfterInitialise

	/**
	 * Checks the result of the calc check submittet by the contact form
	 *
	 * @param $contact
	 * @param $post
	 *
	 * @return mixed true on success / JExecption on failure
	 */
	public function onValidateContact($contact, $post)
	{
		$option = JRequest::getWord('option');
		$app = JFactory::getApplication();

		if ($app->isAdmin())
		{
			return true;
		}

		if ($this->params->get('contact') AND $option == 'com_contact')
		{
			if ($this->performChecks())
			{
				return true;
			}

			// Get the ID of the contact
			$id = JRequest::getCmd('id');

			$returnURI = JURI::current().'?option=com_contact&view=contact&id='.$id.'&essp_err=check_failed';
			
			$this->redirect($returnURI);
		}
		
		return true;
	} // End of function onValidateContact

	/**
	 * Checks the result of the checks submittet by the registration form
	 *
	 * @param $user
	 * @param $isnew bool
	 *
	 * @return mixed true on succes - jexit() on failure as com_user does not hande plugin return values
	 */
	public function onUserBeforeSave($user, $isnew, $new)
	{
		$option = JRequest::getWord('option');
		$app = JFactory::getApplication();

		if ($app->isAdmin() OR !$isnew)
		{
			return true;
		}

		if (($this->params->get('user_reg') AND $option == 'com_users')  OR ($this->params->get('communitybuilder') AND $option == 'com_comprofiler'))
		{
			if ($this->performChecks())
			{
				return true;
			}

			// Checks failed
			$option = JRequest::getWord('option');
			
			if ($option == 'com_comprofiler')
			{
				$returnURI = JURI::current().'?option=com_comprofiler&task=registers&essp_err=check_failed';
			}
			else
			{
			$returnURI = JURI::current().'?option=com_users&view=registration&essp_err=check_failed';
			}
			$this->redirect($returnURI);
		}
		
		return true;
	} // End of function onBeforeStoreUser

	/**
	 * checks the result of the form field checks from request
	 *
	 * @access private
	 *
	 * @return bool true on success
	 */
	private function performChecks()
	{
		// Calc check
		if ($this->params->get('type_calc'))
		{
			if ($_SESSION["rot13"] == 1)
			{
				$spamcheckresult = base64_decode(str_rot13($_SESSION["spamcheckresult"]));
			}
			else
			{
				$spamcheckresult = base64_decode($_SESSION["spamcheckresult"]);
			}
			$spamcheck = JRequest::getInt($_SESSION["spamcheck"], '', 'post');

			if (!is_numeric($spamcheckresult) || $spamcheckresult != $spamcheck)
			{
				return false; // Failed
			}
			unset($_SESSION["spamcheckresult"]);
			unset($_SESSION["spamcheck"]);
			unset($_SESSION["rot13"]);
		}

		// Hidden field
		if ($this->params->get('type_hidden'))
		{
			if (JRequest::getVar($_SESSION["hidden_field"], '', 'post'))
			{
				return false; // Hidden field was filled out - failed
			}
			unset($_SESSION["hidden_field"]);
		}

		// Time lock
		if($this->params->get('type_time'))
		{
			if (time() - $this->params->get('type_time_sec') <= $_SESSION["time"])
			{
				return false; // Submitted too fast - failed
			}
			unset($_SESSION["time"]);
		}

		// Own Question
		// Conversion to lower case
		if ($this->params->get('question'))
		{
			$answer = strtolower(JRequest::getString($_SESSION["question"], '', 'post'));

			if ($answer != strtolower($this->params->get('question_a')))
			{
				return false; // Question wasn't answered - failed
			}
			unset($_SESSION["question"]);
		}

		// StopForumSpam - Check the IP Address
		// Further informations: http://www.stopforumspam.com
		if ($this->params->get('stopforumspam'))
		{
			$url = 'http://www.stopforumspam.com/api?ip='.$_SESSION["ip"];
			
			// Function test - Comment out to test - Important: Enter a active Spam-IP
			// $ip = '109.230.246.224';
			// $url = 'http://www.stopforumspam.com/api?ip='.$ip;
			
			$response = false;
			$is_spam = false;

			if (function_exists('curl_init'))
			{
				$ch = curl_init($url);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				$response = curl_exec($ch);
				curl_close($ch);
			}

			if ($response)
			{
				preg_match('#<appears>(.*)</appears>#', $response, $out) ;
				$is_spam = $out[1];
			}
			else
			{
				$response =@ fopen($url, 'r');

				if ($response)
				{
					while (!feof($response))
					{
						$line = fgets($response, 1024);

						if (preg_match('#<appears>(.*)</appears>#', $line, $out))
						{
							$is_spam = $out[1];
							break;
						}
					}
					fclose($response);
				}
			}
			
			if ($is_spam == 'yes' AND $response == true)
			{
				return false; // Spam-IP - failed
			}
		}
		// Honeypot Project
		// Further informations: http://www.projecthoneypot.org/home.php
		// BL ACCESS KEY - http://www.projecthoneypot.org/httpbl_configure.php
		if ($this->params->get('honeypot'))
		{
			require_once(dirname(__FILE__).DS.'easycalccheckplus'.DS.'honeypot.php');
			$http_blKey = $this->params->get('honeypot_key');

			if ($http_blKey)
			{
				$http_bl = new http_bl($http_blKey);
				$result = $http_bl->query($_SESSION["ip"]);

				// Function test - Comment out to test - Important: Enter a active Spam-IP
				// $ip = '216.198.139.38';
				// $result = $http_bl->query($ip);
				
				if ($result == 2)
				{
					return false;
				}
			}
		}
		// AKISMET
		// Further informations: http://akismet.com/
		if ($this->params->get('akismet'))
		{
			require_once(dirname(__FILE__).DS.'easycalccheckplus'.DS.'akismet.php');
			$WordPressAPIKey = $this->params->get('akismet_key');

			if ($WordPressAPIKey)
			{
				$request = JRequest::get();

				$MyBlogURL = JURI::getInstance()->toString();

				$name = '';
				$email = '';
				$url = '';
				$comment = '';

				if ($request['option'] == 'com_contact')
				{
					$name = $request['name'];
					$email = $request['email'];
					$comment = $request['text'];
				}
				elseif ($request['option'] == 'com_users' OR $request['option'] == 'com_comprofiler')
				{
					if (isset($request['username']))
					{
						$name = $request['username'];
					}
					if (isset($request['checkemail'])) // CB - Forgot Login
					{
						$email = $request['checkemail'];
					}
					elseif (isset($request['email']))
					{
						$email = $request['email'];
					}
				}
				elseif ($request['option'] == 'com_easybookreloaded')
				{
					$name = $request['gbname'];
					$email = $request['gbmail'];
					$comment = $request['gbtext'];
					if (isset($request['gbpage']))
					{
						$url = $request['gbpage'];
					}
				}
				elseif ($request['option'] == 'com_phocaguestbook')
				{
					$name = $request['pgusername'];
					$email = $request['email'];
					$comment = $request['pgbcontent'];
				}

				$akismet = new Akismet($MyBlogURL ,$WordPressAPIKey);
				$akismet->setCommentAuthor($name);
				$akismet->setCommentAuthorEmail($email);
				$akismet->setCommentAuthorURL($url);
				$akismet->setCommentContent($comment);

				if($akismet->isCommentSpam())
				{
					return false;
				}
			}
		}
		// ReCaptcha
		// Further informations: http://www.google.com/recaptcha
		if ($this->params->get('recaptcha') AND $this->params->get('recaptcha_publickey') AND $this->params->get('recaptcha_privatekey'))
		{
			require_once(dirname(__FILE__).DS.'easycalccheckplus'.DS.'recaptchalib.php');
			$privatekey = $this->params->get('recaptcha_privatekey');

			$request = JRequest::get();

			$resp = recaptcha_check_answer($privatekey, $_SESSION["ip"], $request['recaptcha_challenge_field'], $request['recaptcha_response_field']);

			if (!$resp->is_valid)
			{
				return false;
			}
		}
		// Botscout - Check the IP Address
		// Further informations: http://botscout.com/
		if ($this->params->get('botscout') AND $this->params->get('botscout_key'))
		{
			$url = 'http://botscout.com/test/?ip='.$_SESSION["ip"].'&key='.$this->params->get('botscout_key');
			
			// Function test - Comment out to test - Important: Enter a active Spam-IP
			// $ip = '87.103.128.199';
			// $url = 'http://botscout.com/test/?ip='.$ip.'&key='.$this->params->get('botscout_key');
			
			$response = false;
			$is_spam = false;

			if (function_exists('curl_init'))
			{
				$ch = curl_init($url);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				$response = curl_exec($ch);
				curl_close($ch);
			}

			if ($response)
			{
				$is_spam = substr($response, 0, 1);
			}
			else
			{
				$response =@ fopen($url, 'r');

				if ($response)
				{
					while (!feof($response))
					{
						$line = fgets($response, 1024);

						$is_spam = substr($line, 0, 1);
					}
					fclose($response);
				}
			}
			
			if ($is_spam == 'Y' AND $response == true)
			{
				return false; // Spam-IP - failed
			}
		}
		// Mollom
		// Further informations: http://mollom.com/
		if ($this->params->get('mollom') AND $this->params->get('mollom_publickey') AND $this->params->get('mollom_privatekey'))
		{
			require_once(dirname(__FILE__).DS.'easycalccheckplus'.DS.'mollom.php');
			
			Mollom::setPublicKey($this->params->get('mollom_publickey'));
			Mollom::setPrivateKey($this->params->get('mollom_privatekey'));

			$servers = Mollom::getServerList();
			
			$request = JRequest::get();

			$name = '';
			$email = '';
			$url = '';
			$comment = '';

			if ($request['option'] == 'com_contact')
			{
				$name = $request['name'];
				$email = $request['email'];
				$comment = $request['text'];
			}
			elseif ($request['option'] == 'com_users' OR $request['option'] == 'com_comprofiler')
			{
				if (isset($request['username']))
				{
					$name = $request['username'];
				}
				if (isset($request['checkemail'])) // CB - Forgot Login
				{
					$email = $request['checkemail'];
				}
				elseif (isset($request['email']))
				{
					$email = $request['email'];
				}
			}
			elseif ($request['option'] == 'com_easybookreloaded')
			{
				$name = $request['gbname'];
				$email = $request['gbmail'];
				$comment = $request['gbtext'];
				if (isset($request['gbpage']))
				{
					$url = $request['gbpage'];
				}
			}
			elseif ($request['option'] == 'com_phocaguestbook')
			{
				$name = $request['pgusername'];
				$email = $request['email'];
				$comment = $request['pgbcontent'];
			}

			$feedback = Mollom::checkContent(null, null, $comment, $name, $url, $email);

			if ($feedback['spam'] == 'spam')
			{
				return false;
			}
		}

		unset($_SESSION["ip"]);
		return true;
	} // End of function performChecks

	/**
	 * redirect function
	 *
	 * @access private
	 *
	 */
	private function redirect($returnURI)
	{
		// PHP Redirection
		header('Location: '.$returnURI);

		// JS Redirection
		?>
			<script type="text/javascript">window.location = '<?php echo $returnURI; ?>'</script>
		<?php

		// White page - if redirection doesn't work
		echo JText::_('YOUHAVENOTRESOLVEDOURSPAMCHECK');
		jexit();
	} // Ende of function redirect

	/**
	 * returns a random string
	 *
	 * @access private
	 *
	 * @return random string
	 */
	private function random()
	{
		$pw = '';
		// 1. character has to be a letter
		$characters = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
		$array_a = explode(",",$characters);
		$z = mt_rand(0,25);
		$pw .= "".$array_a[$z]."";
		// other characters arbitrarily
		$characters = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9";
		$array_b = explode(",",$characters);
		$pw_l = mt_rand(4,12);
		for ($i=0; $i < $pw_l; $i++)
		{
			srand((double)microtime()*1000000);
			$z = mt_rand(0,35);
			$pw .= "".$array_b[$z]."";
		}
		return $pw;
   } // End of function random

   	/**
	 * converts numbers into strings
	 *
	 * @access private
	 *
	 * @return string of a number
	 */
	private function converttostring($x)
	{
		// Probability 2/3 for conversion
		$random = mt_rand(1,3);

		if ($random != 1)
		{
			if ($x > 20)
			{
				return $x;
			}
			else
			{
				// Names of the numbers are read from language file
				$names = array(JText::_('JNULL'), JText::_('ONE'), JText::_('TWO'), JText::_('THREE'), JText::_('FOUR'), JText::_('FIVE'), JText::_('SIX'), JText::_('SEVEN'), JText::_('EIGHT'), JText::_('NINE'), JText::_('TEN'), JText::_('ELEVEN'), JText::_('TWELVE'), JText::_('THIRTEEN'), JText::_('FOURTEEN'), JText::_('FIFTEEN'), JText::_('SIXTEEN'), JText::_('SEVENTEEN'), JText::_('EIGHTEEN'), JText::_('NINETEEN'), JText::_('TWENTY'));
			return $names[$x];
			}
		}
		else
		{
			return $x;
		}
	} // End of function converttostring
} // End of class